class TreeNode{
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int val){
        this.val = val;
    }
}

public class BinarySearchTree {
    public TreeNode root = null;

    //查找
    public TreeNode search(int key){
        TreeNode cur = root;
        while (cur != null){
            if (cur.val < key){
                cur = cur.right;
            }else if (cur.val > key){
                return cur;
            }else {
                cur = cur.left;
            }
        }
        return null;
    }

    //插入:对于二叉搜索树来说，插入的数据一定是在叶子节点
    public boolean insert(int key){
        if (root == null){
            root = new TreeNode(key);
        }
        TreeNode parent = root;
        TreeNode cur = root;
        while (cur != null){
            if (cur.val > key){
                parent = cur;
                cur = cur.left;
            }else if (cur.val < key){
                parent = cur;
                cur = cur.right;
            }else {
                return false;//不能有相同的值
            }
        }
        if (parent.val > key){
            parent.left = new TreeNode(key);
        }else {
            parent.right = new TreeNode(key);
        }
        return true;
    }

    //删除
    public void remove(int key){
        TreeNode cur = root;
        TreeNode parent = cur;
        while (cur != null){
            if (cur.val == key){
                removeNode(parent, cur);
                break;
            }else if (cur.val < key){
                parent = cur;
                cur = cur.right;
            }else {
                parent = cur;
                cur = cur.left;
            }
        }
    }
    public void removeNode(TreeNode parent, TreeNode cur){
        if (cur.left == null){
            if (cur == root){
                root = cur.right;
            }else if (cur == parent.left){
                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        }else if (cur.right == null){
            if (cur == root){
                root = cur.left;
            }else if (cur == parent.left){
                parent.left = cur.left;
            }else {
                parent.right = cur.left;
            }
        }else {
            TreeNode targetParent = cur;
            TreeNode target = cur.right;
            while (target.left != null){
                targetParent = target;
                target = target.left;
            }
            cur.val = target.val;
            if (target == targetParent.left){
                targetParent.left = target.right;
            }else {
                targetParent.right = target.right;
            }
        }
    }
}